from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
import atom.url
import gdata.service
import gdata.alt.appengine
import settings
import cgi


class Fetcher(webapp.RequestHandler):

    def fetch_feed(self, client, feed_url):
        try:
            response = client.Get(feed_url, converter=str)
            self.response.out.write(cgi.escape(response))
        except gdata.service.RequestError, request_error:
            # If fetching fails, then tell the user that they need to login to
            # authorize this app by logging in at the following URL.
            if request_error[0]['status'] == 401:
                # Get the URL of the current page so that our AuthSub request will
                # send the user back to here.
                self.response.out.write(
                    'Click here to authorize this application to view the feed</a>')
            else:
                self.response.out.write(
                    'Something went wrong, here is the error object: %s ' % (
                        str(request_error[0])))
  
    def get(self):
        next_url = atom.url.Url('http', settings.HOST_NAME, path='/step1')

        self.response.out.write("""<html><body>""")
        self.response.out.write('Version: 0.10<br>')
        self.response.out.write("""request uri: %s <br>""" % self.request.uri)
        
        # Initialize a client to talk to Google Data API services.
        client = gdata.service.GDataService()
        gdata.alt.appengine.run_on_appengine(client)


        user = users.get_current_user()
        if user:
          self.response.out.write("Hello, %s<br>" % user.nickname())
        else:
          self.response.out.write("Hello, Anonymous<br>")
          self.redirect(users.create_login_url(self.request.uri))

        auth_token = gdata.auth.extract_auth_sub_token_from_url(self.request.uri)

        #if token already available do something
        if auth_token:
          self.response.out.write("""auth_token: %s <br>""" % auth_token)
          session_token = client.upgrade_to_session_token(auth_token)
          
          if session_token and users.get_current_user():
            self.response.out.write("""session_token: %s <br>""" % session_token)
            client.token_store.add_token(session_token)
          elif session_token:
            self.response.out.write("""session_token2: %s <br>""" % session_token)
            client.current_token = session_token

        #else ask for authorization
        else:
          # Generate the AuthSub URL and write a page that includes the link
          self.response.out.write("""
              <a href="%s">Request token for the Google Documents Scope</a>
              """ % client.GenerateAuthSubURL(next_url,
                  ('http://docs.google.com/feeds/',), secure=False, session=True))

        feed = "http://docs.google.com/feeds/documents/private/full"
        self.fetch_feed(client, feed)
          
        self.response.out.write("""</body></html>""")

def main():
    application = webapp.WSGIApplication([('/.*', Fetcher),], debug=True)
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
